/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package invitator.mail;

import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 *
 * @author muller
 */
public class MailTool {
    
    public static void main(String args[]){
        ConnectionMailBean cmb = new ConnectionMailBean();
        cmb.setPort("25");
        cmb.setSocketFactoryFallback(true);
        cmb.setQuitwait(false);
        cmb.setHost("smtp.gmail.com");
        cmb.setAuth(true);
        cmb.setStarttlsEnable(true);
        cmb.setPassword("");
        cmb.setLogin("mikolaj.muller@espeo.pl");
        
        MessageMailBean mmb = new MessageMailBean();
        mmb.setFrom_email("mikolaj.muller@espeo.pl");
        mmb.setFrom_name("miki");
        mmb.setReplyTo("mikolaj.muller@espeo.pl");
        mmb.setSubject("topic");
        mmb.setTo_email("mikolaj.muller@espeo.pl");
        mmb.setBody("dd");
        
        send(cmb, mmb);
    }

    public static boolean send(ConnectionMailBean cm, MessageMailBean mmb) {
        boolean sent = false;
        try {
            Properties prop = receivePropFromConnection(cm);

            Session session = Session.getDefaultInstance(prop);

            Message msg = new MimeMessage(session);
            msg.setSubject(mmb.getSubject());

            InternetAddress from = new InternetAddress(mmb.getFrom_email(), mmb.getFrom_name());
            InternetAddress to = new InternetAddress(mmb.getTo_email());
            msg.addRecipient(Message.RecipientType.TO, to);

            // add bcc if not null
            if ((mmb.getBcc_email() != null) && (!mmb.getBcc_email().equals(""))) {
                msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(mmb.getBcc_email()));
            }

            msg.setFrom(from);

            // set reply to email address
            InternetAddress[] replyToAddress = new InternetAddress[1];
            replyToAddress[0] = new InternetAddress(mmb.getReplyTo());
            msg.setReplyTo(replyToAddress);

            Multipart multipart = new MimeMultipart("related");

            BodyPart htmlPart = new MimeBodyPart();
            if (mmb.getType() != null && mmb.getType().equals("html")) {
                htmlPart.setContent(mmb.getBody(), "text/html");
            } else {
                htmlPart.setContent(mmb.getBody(), "text/plain");
            }

            multipart.addBodyPart(htmlPart);
            msg.setContent(multipart);

            Transport transport = session.getTransport("smtp");
            transport.connect(cm.getLogin(), cm.getPassword());
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

            sent = true;
            System.out.println("[MailTool] mail sent successfully ...");

        } catch (Exception e) {
            System.err.println("[MailTool] send() : " + e.getMessage());
            e.printStackTrace();
        }

        return sent;
    }

    private static Properties receivePropFromConnection(ConnectionMailBean cm) {
        Properties prop = new Properties();
        prop.put("mail.smtp.port", cm.getPort());
        prop.put("mail.smtp.socketFactory.fallback", cm.isSocketFactoryFallback());
        prop.put("mail.smtp.quitwait", cm.isQuitwait());
        prop.put("mail.smtp.host", cm.getHost());
        prop.put("mail.smtp.auth", cm.isAuth());
        prop.put("mail.smtp.starttls.enable", cm.isStarttlsEnable());
        return prop;
    }

    public boolean messageIsValid(MessageMailBean messageMailBean) throws Exception {
        StringBuilder sb = new StringBuilder();
        if (messageMailBean.getReplyTo() == null) {
            sb.append("Mail has to have recipient name\n");
        }

        if (messageMailBean.getTo_email() == null) {
            sb.append("Mail has to have recipient email\n");
        }

        if (messageMailBean.getFrom_name() == null) {
            sb.append("Mail has to have sender name\n");
        }

        if (messageMailBean.getFrom_email() == null) {
            sb.append("Mail has to have sender email\n");
        }

        if (messageMailBean.getSubject() == null) {
            sb.append("Mail has to have subject\n");
        }
        
        if (messageMailBean.getBody() == null) {
            sb.append("Mail has to have body\n");
        }

        if (sb.length() != 0) {
            throw new Exception(sb.toString());
        }

        return true;
    }
}
